package com.heliang.util;

import java.lang.reflect.Field;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.text.SimpleDateFormat;
import java.util.Collections;
import java.util.Date;
import java.util.Enumeration;
import java.util.LinkedHashSet;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager.NameNotFoundException;
import android.graphics.Paint;
import android.graphics.Paint.FontMetrics;
import android.net.ConnectivityManager;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.view.View;
import android.view.inputmethod.InputMethodManager;

import com.heliang.common.FileLog;

public class AppUtil
{

    /**
     * 获得一行文字高度
     * @param fontSize
     * @return
     */
    public static int getFontHeight(float fontSize)
    {
        Paint paint = new Paint();
        paint.setTextSize(fontSize);
        FontMetrics fm = paint.getFontMetrics();
        return (int) Math.ceil(fm.descent - fm.top) + 2;
    }

    /**
     * 获得一行文字宽度
     * @param fontSize
     * @return
     */
    public static int getFontWidth(float fontSize)
    {
        Paint paint = new Paint();
        paint.setTextSize(fontSize);

        return (int) paint.measureText("我", 0, 1);
    }

    /**
     * 判断某个包名的应用程序是否安装了
     * @param context
     * @param packagename
     * @return
     */
    public static boolean isInstall(Context context, String packagename)
    {
        PackageInfo packageInfo;
        boolean result = true;
        try
        {
            packageInfo = context.getPackageManager().getPackageInfo(packagename, 0);

        }
        catch (NameNotFoundException e)
        {
            packageInfo = null;
            e.printStackTrace();
        }
        if (packageInfo == null)
        {
            // System.out.println("not installed");
            result = false;
        }
        return result;
    }

    /**
     * 获取文字数目
     * @param width
     * @param fontSize
     * @return
     */
    public static int getWordCount(int width, float fontSize)
    {
        return width / getFontWidth(fontSize);
    }

    /**
     * 字符半角化
     * @param input
     * @return
     */
    public static String ToDBC(String input)
    {
        char[] c = input.toCharArray();
        for (int i = 0; i < c.length; i++)
        {
            if (c[i] == 12288)
            {
                c[i] = (char) 32;
                continue;
            }
            if (c[i] > 65280 && c[i] < 65375)
                c[i] = (char) (c[i] - 65248);
        }
        return new String(c);
    }

    /**
     * 半角转全角：
     * @param input
     * @return
     */
    public static String ToSBC(String input)
    {
        char[] c = input.toCharArray();
        for (int i = 0; i < c.length; i++)
        {
            if (c[i] == 32)
            {
                c[i] = (char) 12288;
                continue;
            }

            if (c[i] < 127 && c[i] > 32)
                c[i] = (char) (c[i] + 65248);
        }

        return new String(c);
    }

    /**
     * dip转px
     * @param context
     * @param dipValue
     * @return
     */
    public static int dip2px(Context context, float dipValue)
    {
        final float scale = context.getResources().getDisplayMetrics().density;
        Log.e(Constants.TAG, "scale:" + scale);
        return (int) (dipValue * scale + 0.5f);
    }

    /**
     * px转dip
     * @param context
     * @param pxValue
     * @return
     */
    public static int px2dip(Context context, float pxValue)
    {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (pxValue / scale + 0.5f);
    }

    /**
     * 根据两点经纬度计算距离　单位千米
     * @param lat1 位置1纬度
     * @param lat2 位置2纬度
     * @param lon1 位置1经度
     * @param lon2 位置2经度
     * @return distance
     */
    public static double getDistatce(double lat1, double lat2, double lon1, double lon2)
    {
        double R = 6378.137; // 地球半径，单位千米
        double distance = 0.0;
        double dLat = (lat2 - lat1) * Math.PI / 180;
        double dLon = (lon2 - lon1) * Math.PI / 180;
        double a = Math.sin(dLat / 2) * Math.sin(dLat / 2) + Math.cos(lat1 * Math.PI / 180) * Math.cos(lat2 * Math.PI / 180)
                * Math.sin(dLon / 2) * Math.sin(dLon / 2);
        distance = (2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a))) * R;
        return distance;
    }

    /**
     * 获取本地ip
     * @return ip 如123.12.23.66
     */
    public static String getLocalIpAddress()
    {
        try
        {
            for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();)
            {
                NetworkInterface intf = en.nextElement();
                for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();)
                {
                    InetAddress inetAddress = enumIpAddr.nextElement();
                    if (!inetAddress.isLoopbackAddress())
                    {
                        return inetAddress.getHostAddress().toString();
                    }
                }
            }
        }
        catch (SocketException ex)
        {
            // Log.e("WifiPreference IpAddress", ex.toString());
            FileLog.log("AppUtil.getLocalIpAddress" + ex.getMessage());
        }
        return null;
    }

    /**
     * 隐藏键盘
     * @param context
     * @param v
     */
    public static void hideSoftInput(Context context, View v)
    {
        InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);

        if (imm.isActive())
        {
            imm.hideSoftInputFromWindow(v.getApplicationWindowToken(), 0);
        }
    }

    /**
     * 打开键盘
     * @param context
     * @param v
     */
    public static void opentSoftInput(Context context, View v)
    {
        InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);

        imm.showSoftInput(v, 0);
    }

    /**
     * 打开一个进度对话框
     * @param context
     * @param strContent
     * @return
     */
    public static ProgressDialog showDialog(Context context, String strContent)
    {
        if (context != null)
        {
            ProgressDialog infoDialog = new ProgressDialog(context);
            infoDialog.setMessage(strContent);
            infoDialog.show();
            return infoDialog;
        }
        return null;
    }

    /**
     * 隐藏一个进度对话框
     * @param infoDialog
     */
    public static void dismissDialog(ProgressDialog infoDialog)
    {
        if (infoDialog != null)
        {
            infoDialog.dismiss();
        }
        infoDialog = null;
    }

    /**
     * 检测是否是3G网络和wifi状态
     * @return true/false
     */
    public static boolean checkNetworkInfo(Context context)
    {
        ConnectivityManager conMan = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); // mobile
                                                                                                                   // 3G
                                                                                                                   // Data
                                                                                                                   // Network
        int type = conMan.getActiveNetworkInfo().getType();
        int subType = conMan.getActiveNetworkInfo().getSubtype();

        if (type == ConnectivityManager.TYPE_WIFI)
        {
            return true;
        }
        else if (type == ConnectivityManager.TYPE_MOBILE)
        {
            switch (subType)
            {
                case TelephonyManager.NETWORK_TYPE_1xRTT:
                    return false; // ~ 50-100 kbps
                case TelephonyManager.NETWORK_TYPE_CDMA:
                    return false; // ~ 14-64 kbps
                case TelephonyManager.NETWORK_TYPE_EDGE:
                    return false; // ~ 50-100 kbps
                case TelephonyManager.NETWORK_TYPE_EVDO_0:
                    return true; // ~ 400-1000 kbps
                case TelephonyManager.NETWORK_TYPE_EVDO_A:
                    return true; // ~ 600-1400 kbps
                case TelephonyManager.NETWORK_TYPE_GPRS:
                    return false; // ~ 100 kbps
                case TelephonyManager.NETWORK_TYPE_HSDPA:
                    return true; // ~ 2-14 Mbps
                case TelephonyManager.NETWORK_TYPE_HSPA:
                    return true; // ~ 700-1700 kbps
                case TelephonyManager.NETWORK_TYPE_HSUPA:
                    return true; // ~ 1-23 Mbps
                case TelephonyManager.NETWORK_TYPE_UMTS:
                    return true; // ~ 400-7000 kbps
                    // NOT AVAILABLE YET IN API LEVEL 7
                    // case Connectivity.NETWORK_TYPE_EHRPD:
                    // return true; // ~ 1-2 Mbps
                    // case Connectivity.NETWORK_TYPE_EVDO_B:
                    // return true; // ~ 5 Mbps
                    // case Connectivity.NETWORK_TYPE_HSPAP:
                    // return true; // ~ 10-20 Mbps
                    // case Connectivity.NETWORK_TYPE_IDEN:
                    // return false; // ~25 kbps
                    // case Connectivity.NETWORK_TYPE_LTE:
                    // return true; // ~ 10+ Mbps
                    // Unknown
                case TelephonyManager.NETWORK_TYPE_UNKNOWN:
                    return false;
                default:
                    return false;
            }
        }
        else
        {
            return false;
        }
    }

    /**
     * 合并两个Integer[]数组并去重
     * @return
     */
    @SuppressWarnings("unchecked")
    public static Integer[] mergeIntArray(Integer[] infoIds, Integer[] infoDelIds)
    {

        @SuppressWarnings("rawtypes")
        LinkedHashSet set = new LinkedHashSet();
        Collections.addAll(set, infoIds);
        Collections.addAll(set, infoDelIds);

        Integer[] oMergeIds = new Integer[set.size()];
        oMergeIds = (Integer[]) set.toArray(new Integer[set.size()]);

        return oMergeIds;
    }

    /**
     * 获取状态栏高度
     * @param context
     * @return
     */
    public static int getStatusHeight(Context context)
    {
        Class<?> c = null;
        Object obj = null;
        Field field = null;
        int x = 0, sbar = 0;
        try
        {
            c = Class.forName("com.android.internal.R$dimen");
            obj = c.newInstance();
            field = c.getField("status_bar_height");
            x = Integer.parseInt(field.get(obj).toString());
            sbar = context.getResources().getDimensionPixelSize(x);
        }
        catch (Exception e)
        {

        }
        return sbar;
    }

    /**
     * 获取整数时间的字符串格式
     * @param time
     * @return
     */
    public static String getDataFormatString(long time)
    {

        SimpleDateFormat m = new SimpleDateFormat("yyyy年MM月dd日 HH:mm");
        String theStr = m.format(new Date(time * 1000));
        String currentStr = m.format(new Date());
        String ymd1 = theStr.substring(0, 11);
        String ym1 = theStr.substring(0, 8);
        String ymd2 = currentStr.substring(0, 11);
        String ym2 = currentStr.substring(0, 8);
        if (ymd1.equals(ymd2))
        {
            return " 今  天 " + theStr.substring(11);
        }
        else if (ym1.equals(ym2))
        {
            int d1 = Integer.parseInt(theStr.substring(8, 10));
            int d2 = Integer.parseInt(currentStr.substring(8, 10));
            if (d2 - d1 == 1)
            {
                return " 昨  天 " + theStr.substring(11);
            }
        }
        return theStr.substring(5);
    }
}
